<!-- 绘制分区 -->
<template>
  <div class="app-container">
    <TopMenu :data-list="topDataLabel" @tabsChange="tabsChange" />
    <div class="main-info-container main-info-point-container">
      <div v-show="isPlan" id="hello-map" class="main-left"/>
      <div v-show="!isPlan" id="addImg" class="main-left cur" @click="uploadImg"/>
      <input id="upload" name="plan" type="file" accept="image/*" @change="upload">
      <div id="eagle-map" />
      <div id="eagle-map2" />
      <!--<div id="hello-map" :style="{backgroundImage:'url(' + plotPartitionImgBg + ')'}" class="main-left"/> -->
      <div class="main-rigth">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="分区管理" name="first">
            <!-- 查询结果 -->
            <el-table v-loading="listLoadingPartition" ref="tablePartition" :data="listPartition" size="small" element-loading-text="正在查询中。。。" stripe border el-table-column fit highlight-current-row>
              <el-table-column type="selection" width="50" label="选择" />
              <el-table-column type="index" width="50" label="序号" />
              <el-table-column align="center" label="房间/分区名称" prop="name" />
              <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <a href="javascript:void(0);" class="table-btn" @click="drawPartition(scope.row)">绘制</a>
                </template>
              </el-table-column>
              <div slot="empty">
                暂无数据
                <!-- <a href="javascript:void(0);" class="table-btn" @click="addPartition"> 添加</a> -->
              </div>
            </el-table>
            <el-button type="danger" style="margin-top:10px" size="small" icon="el-icon-delete" @click.native="deletePartition">清空标记</el-button>
            <el-button type="primary" style="margin-top:10px" size="small" icon="el-icon-plus" @click.native="addPartition">添加分区</el-button>
            <pagination v-show="totalPartition>0" :total="totalPartition" :page.sync="listQueryPartition.page" :limit.sync="listQueryPartition.offset" @pagination="getListPartition" />
          </el-tab-pane>
          <el-tab-pane label="设备管理" name="second">
            <!-- 查询结果 -->
            <el-table v-loading="listLoadingEquipment" ref="tableEquipment" :data="listEquipment" size="small" element-loading-text="正在查询中。。。" stripe border el-table-column fit highlight-current-row>
              <el-table-column type="selection" width="50" label="选择" />
              <el-table-column type="index" width="50" label="序号" />
              <el-table-column align="center" label="设备名称" prop="mname" />
              <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <a href="javascript:void(0);" class="table-btn" @click="drawEquipment(scope.row)">标记</a>
                </template>
              </el-table-column>
              <div slot="empty">
                暂无数据
                <!-- <a href="javascript:void(0);" class="table-btn" @click="addEquipment"> 添加</a> -->
              </div>
            </el-table>
            <el-button type="danger" style="margin-top:10px" size="small" icon="el-icon-delete" @click.native="deletePartition">清空标记</el-button>
            <el-button type="primary" style="margin-top:10px" size="small" icon="el-icon-plus" @click.native="addEquipment">添加设备</el-button>
            <pagination v-show="totalEquipment>0" :total="totalEquipment" :page.sync="listQueryEquipment.page" :limit.sync="listQueryEquipment.offset" @pagination="getListEquipment" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <formEquipment
        v-if="dialogVisibleEquipment"
        :dialog-form="dialogFormEquipment"
        :dialog-type="dialogTypeEquipment"
        :dialog-visible.sync="dialogVisibleEquipment"
        @getCancel="handleCancelEquipment"
        @closeBindWarnStandard="handleCloseBindWarnStandardEquipment"
        @submitForm="submitFormEquipment"/>
      <formPartition
        v-if="dialogVisiblePartition"
        :dialog-form="dialogFormPartition"
        :dialog-type="dialogTypePartition"
        :dialog-visible.sync="dialogVisiblePartition"
        @getCancel="handleCancelPartition"
        @closeBindWarnStandard="handleCloseBindWarnStandardPartition"
        @submitForm="submitFormPartition"/>
    </div>
  </div>
</template>
<script>
import $ from 'jquery'
import {
  equipmentList
} from '@/api/equipmentManage'
import {
  partitionList,
  setEquipsPoint,
  setPartition,
  clearPartition,
  clearEquipsPoint
} from '@/api/partition'
import {
  floorList,
  floorUpdate
} from '@/api/park'
import AILabel from 'ailabel'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import TopMenu from '@/components/TopMenu' // 顶部菜单
import formEquipment from './components/formEquipment.vue' // 添加设备
import formPartition from './components/formPartition.vue' // 添加分区
import plotPartitionImg from '@/assets/plotPartition.png'
import markerImg from '@/assets/marker.png'

export default {
  name: 'Order',
  components: {
    Pagination,
    TopMenu,
    formEquipment,
    formPartition
  },
  data() {
    return {
      plotPartitionImg,
      selectType: '',
      plotPartitionImgBg: '',
      dialogTypeEquipment: '绘制分区添加',
      dialogTypePartition: '绘制分区添加',
      // 弹窗信息
      dialogFormEquipment: {
        corp_id: '',
        park_id: '',
        building_id: '',
        floor_id: '',
        zone_id: '',
        park_name: '',
        building_name: '',
        floor_name: '',
        partition_name: '',
        position: '',
        sid: '',
        tid: '',
        mid: '',
        UID: '',
        upperLimit: '',
        lowerLimit: ''
      },
      dialogVisibleEquipment: false,
      dialogFormPartition: {
        zone_id: '',
        corp_id: '',
        corp_name: '',
        park_id: '',
        park_name: '',
        building_id: '',
        building_name: '',
        floor_id: '',
        floor_name: '',
        name: ''
      },
      dialogVisiblePartition: false,
      // tabs页签信息
      activeName: 'first',
      // 顶部选择楼层
      topDataLabel: {
        data: []
      },
      // 表格信息
      listPartition: [],
      listEquipment: [],
      totalPartition: 0,
      totalEquipment: 0,
      listLoadingPartition: false,
      listLoadingEquipment: false,
      listQueryPartition: {
        page: 1,
        offset: 8,
        floor_id: ''
      },
      listQueryEquipment: {
        page: 1,
        offset: 8,
        floor_id: ''
      },
      topListQuery: {
        page: 1,
        limit: 8,
        building_id: ''
      },
      graphicalList: [],
      positionList: [],
      floorData: [],
      isPlan: false,
      gMap: null,
      gFeatureLayer: null,
      selectDataE: {},
      selectDataP: {},
      isFirst: true,
      idC: ''
    }
  },
  computed: {
    // 计算属性
    getPageData() {
      return this.$route.params.buildData
    }
  },
  created() {
    this.$nextTick(function() {
      if (!this.getPageData) {
        this.$router.push({
          name: 'partitionManage'
        })
      } else {
        this.dialogFormPartition.corp_id = this.getPageData.corp_id
        this.dialogFormPartition.park_id = this.getPageData.park_id
        this.dialogFormPartition.building_id = this.getPageData.building_id
        this.dialogFormPartition.floor_id = this.getPageData.floor_id
        this.dialogFormEquipment.corp_id = this.getPageData.corp_id
        this.dialogFormEquipment.park_id = this.getPageData.park_id
        this.dialogFormEquipment.building_id = this.getPageData.building_id
        this.dialogFormEquipment.floor_id = this.getPageData.floor_id
        this.dialogFormEquipment.zone_id = this.getPageData.zone_id
        const that = this
        // 顶部楼层列表
        this.topListQuery.building_id = this.getPageData.building_id
        this.getListTopMenuData()
        setTimeout(function() {
          // 分区列表
          that.listQueryPartition.floor_id = that.getPageData.floor_id
          that.getListPartition()
          // 设备列表
          that.listQueryEquipment.floor_id = that.getPageData.floor_id
          // that.getListEquipment()
        }, 300)
      }
    })
  },
  methods: {
    // 分区列表查询
    getListPartition() {
      const that = this
      if (this.listQueryPartition.floor_id === '') {
        return false
      }
      this.listLoadingPartition = true
      partitionList(this.listQueryPartition)
        .then(response => {
          this.selectDataE = {}
          this.selectDataP = {}
          this.listPartition = []
          response.data.data.data.forEach(function(value, index, array) {
            array[index].is_forbidden = array[index].is_forbidden === 2
            that.listPartition.push(array[index])
            if (that.activeName === 'first') {
              setTimeout(item => {
                if (that.gMap) {
                  that.plotPartitionFn(array[index])
                }
              }, 100)
            }
          })
          this.totalPartition = parseInt(response.data.data.total_count)
          this.listLoadingPartition = false
        })
        .catch((e) => {
          console.log(e)
          this.listPartition = []
          this.totalPartition = 0
          this.listLoadingPartition = false
        })
    },
    // 设备列表查询
    getListEquipment() {
      const that = this
      this.listLoadingEquipment = true
      equipmentList(this.listQueryEquipment)
        .then(response => {
          this.selectDataE = {}
          this.selectDataP = {}
          this.listEquipment = []
          response.data.data.data.forEach(function(value, index, array) {
            that.listEquipment.push(array[index])
            if (that.activeName !== 'first') {
              setTimeout(item => {
                that.signFn(array[index])
              }, 100)
            }
          })
          this.totalEquipment = parseInt(response.data.data.total_count)
          this.listLoadingEquipment = false
        })
        .catch((e) => {
          console.log(e)
          this.listEquipment = []
          this.totalEquipment = 0
          this.listLoadingEquipment = false
        })
    },
    // 顶部楼层查询
    getListTopMenuData(value) {
      const that = this
      floorList(this.topListQuery)
        .then(response => {
          that.topDataLabel.data = []
          that.floorData = []
          var floor_idC = ''
          if (value) {
            floor_idC = value
          } else {
            floor_idC = that.getPageData.floor_id
          }
          response.data.data.data.forEach(function(value, index, array) {
            that.topDataLabel.data.push(array[index].name)
            if (array[index].floor_id === floor_idC) {
              that.topDataLabel.selectName = array[index].name
              that.plotPartitionImgBg = array[index].plan ? array[index].plan : ''
              console.log(array[index])
              if (!array[index].plan) {
                that.$message.warning('请您先去上传平面图！')
                $('#addImg').html('<i class="el-icon-plus"/><div class="add-text"><span>添加新的大屏</span></div>')
                that.isPlan = false
              } else {
                that.isPlan = true
                setTimeout(item => {
                  that.initC()
                }, 100)
              }
            }
            that.floorData.push({
              name: array[index].name,
              id: array[index].floor_id,
              plan: array[index].plan
            })
          })
        })
        .catch((error) => {
          console.log(error)
        })
    },
    timestamp() {
      return new Date().getTime()
    },
    initC() {
      // 添加图片层实例
      if (!this.plotPartitionImgBg) {
        console.log(this.plotPartitionImgBg)
        return false
      }
      this.idC = 'img' + this.timestamp()
      const gImageLayer = new AILabel.Layer.Image(`${this.idC}`, this.plotPartitionImgBg, {
        w: 530,
        h: 300
      }, {
        zIndex: 1
      })
      if (this.gMap) {
        this.gMap.destroy()
      }
      this.gMap = new AILabel.Map('hello-map', {
        zoom: 530,
        cx: 0,
        cy: 0,
        zoomMax: 530,
        zoomMin: 530 / 10,
        autoPan: false,
        drawZoom: false
      })
      this.gMap.addLayer(gImageLayer)
      this.gMap.setMode('pan')
      if (this.activeName === 'first') {
        this.getListPartition()
      } else {
        this.getListEquipment()
      }
    },
    // 顶部切换监听
    tabsChange(data) {
      const that = this
      this.floorData.forEach((item, index) => {
        if (item.name === data) {
          this.dialogFormPartition.floor_id = item.id
          this.dialogFormEquipment.floor_id = item.id
          this.listQueryPartition.floor_id = item.id
          this.listQueryEquipment.floor_id = item.id
          this.plotPartitionImgBg = item.plan
          if (item.plan && item.plan.length > 0) {
            this.isPlan = true
            this.$nextTick(i => {
              that.initC()
            })
          } else {
            this.$message.warning('请您先去上传平面图！')
            $('#addImg').html('<i class="el-icon-plus"/><div class="add-text"><span>添加新的大屏</span></div>')
            this.isPlan = false
          }
        }
      })
    },
    // tabs页签切换
    handleClick() {
      this.selectDataE = {}
      this.selectDataP = {}
      this.initC()
    },
    // 绘制分区
    drawPartition(data) {
      const that = this
      const gFetureStyle = new AILabel.Style({
        fillColor: '#7ECDF8',
        opacity: 1
      })
      const gTextStyle = new AILabel.Style({
        fontColor: '#e73839',
        bgColor: 'transparent'
      })
      const params = {
        zone_id: data.zone_id,
        corp_id: data.corp_id,
        park_id: data.park_id,
        device_id: data.device_id,
        building_id: data.building_id,
        floor_id: data.floor_id,
        nfc_code: data.nfc_code,
        field: data.field
      }
      params.field = params.field && typeof params.field === 'string' ? JSON.parse(params.field) : params.field
      this.selectDataP = data
      this.gMap.setMode('drawRect', gFetureStyle)
      this.gMap.events.on('geometryDrawDone', function(type, points) {
        if (!that.selectDataP.floor_id) {
          return false
        }
        // 生成元素唯一标志（时间戳）
        // 元素添加展示
        that.positionList = points
        that.idC = 'plotFeaNew' + that.timestamp()
        const fea = new AILabel.Feature.Rect(`${that.idC}`, points, {
          name: '中国'
        }, gFetureStyle)
        const text = new AILabel.Text(`text`, {
          pos: {
            x: points[0].x,
            y: points[0].y
          },
          offset: {
            x: 0,
            y: 0
          },
          text: data.name
        }, gTextStyle)
        that.gTextLayer.addText(text)
        that.gFeatureLayer.addFeature(fea)
        params.field = JSON.stringify(that.positionList)
        setPartition(params)
          .then(response => {
            that.$message.success(response.data.message)
            that.initC()
          })
          .catch(() => {})
      })
      // 因为自带编辑功能，故需要以下代码
      this.gMap.events.on('geometryEditDone', (type, activeFeature, points) => {
        console.log(that.selectDataP)
        if (!that.selectDataP.floor_id) {
          return false
        }
        activeFeature.update({
          points
        })
        that.positionList = points
        activeFeature.show()
        params.field = JSON.stringify(that.positionList)
        setPartition(params)
          .then(response => {
            that.$message.success(response.data.message)
            that.initC()
          })
          .catch(() => {})
      })
    },
    // 标记设备
    drawEquipment(data) {
      const that = this
      const params = {
        corp_id: data.corp_id,
        park_id: data.park_id,
        building_id: data.building_id,
        floor_id: data.floor_id,
        zone_id: data.zone_id,
        device_id: data.device_id,
        sid: data.sid,
        tid: data.tid,
        position: data.position,
        mid: data.mid,
        field: data.field
      }
      this.selectDataE = data
      const gTextStyle = new AILabel.Style({
        color: '#0000FF'
      })
      this.gMap.setMode('drawPoint', gTextStyle)
      this.gMap.events.on('mouseDown', xy => {
        if (!that.selectDataE.floor_id) {
          return false
        }
        if (that.positionList.length > 0) {
          that.positionList = []
        }
        that.positionList.push({
          'x': xy.x,
          'y': xy.y
        })
        // 添加标注文字描述
        that.idC = 'eTextNew' + that.timestamp()
        const text = new AILabel.Text(`${that.idC}`, {
          pos: {
            x: xy.x,
            y: xy.y
          },
          offset: {
            x: 0,
            y: 0
          },
          text: data.mname
        }, gTextStyle)
        that.gTextLayer.addText(text)
        // 添加标注
        var options = {
          src: markerImg,
          x: xy.x,
          y: xy.y,
          offset: {
            x: -14,
            y: -36
          }
        }
        that.idC = 'eMarkerNew' + that.timestamp()
        var marker = new AILabel.Marker(`${that.idC}`, options)
        that.gMap.mLayer.addMarker(marker)
        params.field = JSON.stringify(that.positionList)
        setEquipsPoint(params)
          .then(response => {
            that.$message.success(response.data.message)
            that.initC()
          })
          .catch(() => {})
      })
    },
    // 分区管理页签 - 回显列表分区
    plotPartitionFn(data) {
      console.log(JSON.stringify(data))
      // 常用样式声明
      const gFetureStyle = new AILabel.Style({
        fillColor: '#7ECDF8',
        opacity: 1
      })
      // 矢量层实例\添加
      this.idC = 'plotFeatureLayer' + data.zone_id
      this.gFeatureLayer = new AILabel.Layer.Feature(`${this.idC}`, {
        zIndex: 2
      })
      data.field = data.field && typeof data.field === 'string' ? JSON.parse(data.field) : data.field
      this.positionList = []
      const gTextStyle = new AILabel.Style({
        fontColor: '#e73839',
        bgColor: 'transparent'
      })
      this.idC = 'plotText' + data.zone_id
      this.gTextLayer = new AILabel.Layer.Text(`${this.idC}`)
      this.gMap.addLayer(this.gTextLayer)
      this.selectDataP = data
      this.selectType = '绘制'
      this.gMap.addLayer(this.gFeatureLayer)
      // 如果多边形 setMode('drawRect', gFetureStyle)变成drawPolygon
      this.gMap.setMode('pan')
      // 如果多边形 new AILabel.Feature.Rect变成new AILabel.Feature.Polyline
      if (data.field && data.field.length > 0) {
        var obj = data.field && typeof data.field === 'string' ? JSON.parse(data.field) : data.field
        if (obj.length === 0) {
          return false
        }
        this.positionList = obj
        this.idC = 'plotFea' + data.zone_id
        const fea = new AILabel.Feature.Rect(`${this.idC}`, this.positionList, {
          name: '中国'
        }, gFetureStyle)
        this.gFeatureLayer.addFeature(fea)
        // 添加标注文字描述
        const text = new AILabel.Text(`text`, {
          pos: {
            x: obj[0].x,
            y: obj[0].y
          },
          offset: {
            x: 10,
            y: 10
          },
          text: data.name
        }, gTextStyle)
        this.gTextLayer.addText(text)
      }
    },
    // 设备管理页签 - 标记列表设备点位
    signFn(data) {
      this.selectType = '标记'
      this.positionList = []
      const gTextStyle = new AILabel.Style({
        color: '#0000FF'
      })
      if (data.field && data.field.length > 0) {
        var obj = data.field ? JSON.parse(data.field)[0] : ''
        if (obj.length === 0) {
          return false
        }
        this.idC = 'equText' + data.device_id
        this.gTextLayer = new AILabel.Layer.Text(`${this.idC}`)
        this.gMap.addLayer(this.gTextLayer)
        this.positionList.push({
          'x': obj.x,
          'y': obj.y
        })
        // 添加标注文字描述
        this.idC = 'eText' + data.device_id
        const text = new AILabel.Text(`${this.idC}`, {
          pos: {
            x: obj.x,
            y: obj.y
          },
          offset: {
            x: 0,
            y: 0
          },
          text: data.mname
        }, gTextStyle)
        this.gTextLayer.addText(text)
        // 添加标注
        this.idC = 'eMarker' + data.device_id
        const marker = new AILabel.Marker(`${this.idC}`, {
          src: markerImg,
          x: obj.x,
          y: obj.y,
          offset: {
            x: -14,
            y: -36
          }
        })
        this.gMap.mLayer.addMarker(marker)
      }
    },
    // 清除标记
    deletePartition() {
      let data
      let zone_id = '' // 分区id
      let device_id = '' // 设备id
      if (this.activeName === 'first') { // 分区
        if (this.$refs['tablePartition'].selection.length === 0) {
          this.$message.warning('请选择数据！')
          return false
        }
        data = this.$refs['tablePartition'].selection[0]
        this.$refs['tablePartition'].selection.forEach((item, index) => {
          zone_id += item.zone_id + ','
        })
        const params = {
          zone_id: zone_id,
          corp_id: data.corp_id,
          park_id: data.park_id,
          device_id: data.device_id,
          building_id: data.building_id,
          floor_id: data.floor_id,
          field: ''
        }
        clearPartition(params)
          .then(response => {
            this.$message.success(response.data.message)
            this.initC()
          })
          .catch(() => {})
      } else { // 设备
        if (this.$refs['tableEquipment'].selection.length === 0) {
          this.$message.warning('请选择数据！')
          return false
        }
        data = this.$refs['tableEquipment'].selection[0]
        this.$refs['tableEquipment'].selection.forEach((item, index) => {
          device_id += item.device_id + ','
        })
        const params = {
          corp_id: data.corp_id,
          park_id: data.park_id,
          building_id: data.building_id,
          floor_id: data.floor_id,
          zone_id: data.zone_id,
          device_id: device_id,
          sid: data.sid,
          tid: data.tid,
          position: data.position,
          mid: data.mid,
          field: ''
        }
        clearEquipsPoint(params)
          .then(response => {
            this.$message.success(response.data.message)
            this.initC()
          })
          .catch(() => {})
      }
    },
    uploadImg() {
      $('#upload').click()
    },
    upload(e) {
      var file = e.target.files[0]
      const isImage = e.target.files[0].type.substr(0, 5) === 'image'
      if (!isImage) {
        this.$message.error('请上传图片格式!')
        return false
      }
      this.plotPartitionImgBg = URL.createObjectURL(file)
      const that = this
      const image = new window.FormData()
      image.append('plan', file)
      image.append('corp_id', that.getPageData.corp_id)
      image.append('park_id', that.getPageData.park_id)
      image.append('building_id', that.getPageData.building_id)
      var params = {
        floor_id: that.getPageData.floor_id,
        fileType: 'file',
        data: image
      }
      floorUpdate(params)
        .then((res) => {
          const data = res.data
          if (data.code === 40000) {
            that.gMap = new AILabel.Map('hello-map', {
              zoom: 530,
              cx: 0,
              cy: 0,
              zoomMax: 530,
              zoomMin: 530 / 10
            })
            that.gMap.setMode('pan')
            that.getListTopMenuData(that.getPageData.floor_id)
            that.$message.success(data.message)
          } else {
            that.$message.warning(data.message)
          }
        })
        .catch((e) => {
          console.log(e)
        })
    },
    // 弹窗
    // 添加分区
    addEquipment() {
      this.dialogTypeEquipment = '绘制分区添加'
      this.dialogVisibleEquipment = true
    },
    // 添加设备确认
    submitFormEquipment(formName) {
      this.dialogVisibleEquipment = false
    },
    // 关闭添加设备弹窗
    handleCancelEquipment() {
      this.dialogVisibleEquipment = false
      this.initC()
    },
    // 关闭添加设备弹窗
    handleCloseBindWarnStandardEquipment() {
      this.dialogVisibleEquipment = false
      this.initC()
    },
    // 添加分区
    addPartition() {
      this.dialogVisiblePartition = true
    },
    // 添加分区确认
    submitFormPartition(formName) {
      this.dialogVisiblePartition = false
      this.initC()
    },
    // 关闭添加分区弹窗
    handleCancelPartition() {
      this.dialogVisiblePartition = false
      this.initC()
    },
    // 关闭添加分区弹窗
    handleCloseBindWarnStandardPartition() {
      this.dialogVisiblePartition = false
      this.gMap.destroy()
      this.initC()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.app-container {
  overflow: inherit;
}

.main-info-container {
  position: relative;
}

.main-info-point-container {
  padding: 0;
  min-height: 300px;
}

#eagle-map {
  position: absolute;
  left: 200px;
  top: 300px;
  display: none;
}

#eagle-map2 {
  position: absolute;
  left: 0px;
  top: 300px;
  display: none;
}
.cur {
  cursor: pointer;
}

.main-left {
  width: 530px;
  height: 300px;
  line-height: 300px;
  position: absolute;
  overflow: hidden;
  left: 0;
  top: 0;
  background-size: 100%;
  z-index: 11;
  text-align: center;
}

.main-rigth {
  width: 100%;
  padding-left: 550px;
  padding-right: 20px;
  padding-top: 10px;
  padding-bottom: 10px;
  box-sizing: border-box;
  position: relative;
  z-index: 10;
}

#upload {
  display: none;
}
</style>
